package com.hewang.helloandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;

import java.io.IOException;

public class OpenCameraView extends AppCompatActivity implements TextureView.SurfaceTextureListener, SurfaceHolder.Callback{
    private static final String TAG = "com.hewang.helloandroid.openCameraView";

    private static final int CAMERA_OK =1;
    private Camera camera; // camera1.0的API android官网已废弃，建议使用CameraX或者camera2
    private SurfaceView surfaceView; // 用于向用户呈现实时相机预览，可以显示从相机传入的实时图片数据
    private SurfaceHolder holder;
    private Surface surface;
    private int cameraDirection = 0;
    // Activity onCreate生命周期
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 关联布局
        setContentView(R.layout.activity_open_camera_view);

        surfaceView = findViewById(R.id.cameraView);
        // 挂载SurfaceHolder回调监听，当底层的surface被创建或者销毁时，可以收到通知
        holder = surfaceView.getHolder();
        holder.addCallback(this);
        if (ContextCompat.checkSelfPermission(OpenCameraView.this, android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
            //没有权限就在这里申请
            Log.i(TAG, "not camera permission");
            ActivityCompat.requestPermissions(OpenCameraView.this, new String[]{Manifest.permission.CAMERA}, CAMERA_OK);
        }else {
            //说明已经获取到摄像头权限了
            Log.i(TAG, "has camera permission");
        }
        findViewById(R.id.btnSwitch).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              cameraDirection = cameraDirection == 0 ? 1 : 0;
              openCamera();
            };
        });
    }

    private static Camera getCamera(int direction) {
        Camera camera = null;
        try {
            // 为什么要try catch 如果其它应用也在使用相机，则调用Camera.open 会抛出异常
            camera = Camera.open(direction); // // 获取相机实例，后置摄像头0 前置摄像头1, 返回摄像头的实例
        } catch (Exception e) {
            Log.e(TAG, "getCamera: error", e);
            e.printStackTrace();
        }
        return camera;
    }

    /**
     * 打开摄像头
     */
    private void openCamera() {
        releaseCamera(camera);
        try {
            camera = getCamera(cameraDirection);
        } catch (Exception e) {
            Log.e(TAG, "get camera instance error", e);
        }
        // 相机预览默认的屏幕方向是横向, 旋转90度变为正向的
        camera.setDisplayOrientation(90);
        // 获取相机参数
        Camera.Parameters parameters = camera.getParameters(); // 获取相机功能的详细信息
        // 设置预览格式，也就是每一帧的视频格式 YUV420下的NV21
        parameters.setPreviewFormat(ImageFormat.NV21);

        int previeWidth = 1920;
        int previewHeight = 1080;
        parameters.setPreviewSize(previeWidth, previewHeight);
        try {
            camera.setParameters(parameters);
        } catch (Exception e) {
            Log.e(TAG, "openCamera: ", e);
        }

        try {
            camera.setPreviewDisplay(holder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        camera.startPreview();
        // 设置监听获取视频流的每一帧
//        camera.setPreviewCallback(new Camera.PreviewCallback() {
//            @Override
//            public void onPreviewFrame(byte[] bytes, Camera camera) {
//
//            }
//        });
    }

    public void releaseCamera(Camera camera) {
        if (camera != null) {
            camera.setPreviewCallback(null);
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
        Log.d(TAG, "surface created.");
        openCamera();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        Log.d(TAG, "surface changed");
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
        Log.d(TAG, "surface destroyed.");
    }

    @Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int i, int i1) {
        if (surface != null) {
            this.surface = new Surface(surface);
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surfaceTexture, int i, int i1) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surfaceTexture) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surfaceTexture) {

    }
}